<?php
/**
 * Created by PhpStorm.
 * User: shrrung
 * Date: 2017/7/1
 * Time: 20:56
 */
namespace app\index\model;

use think\Db;
use think\Model;

class Essay extends Model
{

    protected $name = 'essay';

    public static function self(){
        return new self();
    }

    public function getEssaysByUid($uid = 0,$field = ''){
        if($uid){
            $this->where('uid',$uid);
        }

        if(!empty($field)){
            $this->field($field);
        }
        return $this->select();
    }

    public function getEssayInfoByEid($eid ='',$field='',$user = [],$unique = ''){
        $this->where(['eid'=>$eid]);
//        if(!empty($field)){
//            $this->field($field);
//        }
        return $this->find();
    }

    public function delEssayByEid($eid = 0,$uid){
        $where['eid'] = $eid;
        if($uid){
            $where['uid'] = $uid;
        }
//        file_put_contents(PUBLIC_PATH.'/error.log',$sql."\r\n",FILE_APPEND);
        return $this->where($where)->delete();
    }

    public function addEssay($data = [],$validate_img_url = false){
        if($data){
            if($validate_img_url){
                $data['img_url'] = $this->arrImgTranToJson($data['img_url']);
            }
            $this->insert($data);
            return true;
        }else{
            return false;
        }
    }

    public function modifyEssayInfoIncOrDec($eid = '',$field,$option = true)
    {
        if($option){
            $res = $this->where('eid',$eid)->setInc($field);
        }else{
            $res = $this->where('eid',$eid)->setDec($field);
        }
        return $this->where('eid',$eid)->find();
    }

    public function essayLikeLog($eid,$uid,$option)
    {
        db('essay_like_log')->insert(['eid'=>$eid,'uid'=>$uid,'target_uid'=>0,'option'=>$option,'create_time'=>date('Y-m-d H:i:s',time())]);
    }

    public function getEssayLikeLog($where = [])
    {
        return db('essay_like_log')->where($where)->find();
    }

    public function deleteEssayLikeLog($eid,$uid)
    {
        return db('essay_like_log')->where(['eid'=>$eid,'uid'=>$uid])->delete();
    }

    //对图片数组进行转化成json
    private function arrImgTranToJson($arr_json){
        if($arr_json){
            return \GuzzleHttp\json_encode($arr_json,true);
        }else{
            return '';
        }
    }

    public function getEssayList($where,$page,$limit)
    {
        return db('essay')->where($where)->where(['status'=>1])->order(['create_time'=>'desc','is_recommend'=>'desc','order'=>'desc'])->page($page)->limit($limit)->select();
    }

    public function getEssayRandomList($page,$limit)
    {
        $eids = Db::query("SELECT t1.eid
FROM `essay` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(eid) FROM `essay`)-(SELECT MIN(eid) FROM `essay`))+(SELECT MIN(eid) FROM `essay`)) AS eid) AS t2 WHERE t1.eid >= t2.eid
ORDER BY t1.eid LIMIT 21");
        $eids = array_column($eids,'eid');
//        var_dump($eids);exit;
        shuffle($eids);
        $eids = implode(',',$eids);
//        var_dump($eids);exit;
        $return = Db::query("select eid,uid,content,img_url,like_count,comment_count,reward_count,create_time from essay where eid in ({$eids}) order by field(eid,{$eids}) limit {$limit}");
        foreach($return as $key=>$essay){
            $user = db('user')->where(['id'=>$essay['uid']])->find();
            if($user){
                $return[$key]['nickname'] = $user['nickname'];
                $return[$key]['avatar']= $user['avatar'];
            }else{
                $return[$key]['nickname'] = '';
                $return[$key]['avatar'] = '';
            }

        }
//        echo count($return);
        return $return;
//        $res = Db::view('essay','eid,uid,content,img_url,like_count,comment_count,reward_count,create_time')
////            ->view('user','nickname,avatar','user.id=essay.uid','LEFT')
//            ->where(['essay.status'=>'1'])
//            ->where('eid','in',$limits)
//            ->page($page)
//            ->limit($limit)
////            ->order()
////            ->fetchSql(true)
//            ->select();
    }

    public function randomNums($min,$max,$limit){
        $numbers = range($min,$max);
        shuffle($numbers);
        return array_slice($numbers,0,$limit);
    }

    public function getEssayFocusList($uid,$page,$limit,$self_uid)
    {
        return Db::view('essay','eid,uid,content,img_url,like_count,comment_count,reward_count,create_time')
            ->view('essay_fans','uid as fans_uid','essay_fans.target_uid=essay.uid','LEFT')
            ->where(['essay_fans.uid'=>$uid,'essay.status'=>'1'])
//            ->whereOr(['user.id'=>$self_uid])
            ->page($page)
            ->limit($limit)
            ->order(['essay.create_time'=>'desc'])
//            ->fetchSql(true)
            ->select();
    }

    public function judgeEssayIsLike($uid,$essay_list)
    {
        if(empty($essay_list)){
            return [];
        }else{
            if(is_mul_array($essay_list)){
                foreach ($essay_list as $key=>$essay) {
                    if(empty($uid)){
                        $essay_list[$key]['is_like'] = 0;
                    }else{
                        $res = db('essay_like_log')->where(['uid'=>$uid,'eid'=>$essay['eid']])->find();
                        if ($res) {
                            $essay_list[$key]['is_like'] = 1;
                        } else {
                            $essay_list[$key]['is_like'] = 0;
                        }
                    }

                }
                return $essay_list;
            }else{
                if(empty($uid)){
                    $essay_list['is_like'] = 0;
                }else{
                    $res = db('essay_like_log')->where(['uid'=>$uid,'eid'=>$essay_list['eid']])->find();
                    if($res){
                        $essay_list['is_like'] = 1;
                    }else{
                        $essay_list['is_like'] = 0;
                    }
                }

                return $essay_list;
            }
        }
    }

    public function judgeEssayCreatorIsFan($uid,$essay_list)
    {
        if(empty($essay_list)){
            return [];
        }else{
            if(is_mul_array($essay_list)){
                foreach ($essay_list as $key=>$essay){
                    if(empty($uid)){
                        $essay_list[$key]['is_fans'] = 0;
                    }else{
                        $res = db('essay_fans')->where(['uid'=>$uid,'target_uid'=>$essay['uid']])->find();
                        if($res){
                            $essay_list[$key]['is_fans'] = 1;
                        }else{
                            $essay_list[$key]['is_fans'] = 0;
                        }
                    }

                }
                return $essay_list;
            }else{
                if(empty($uid)){
                    $essay_list['is_fans'] = 0;
                }else {
                    $res = db('essay_fans')->where(['uid' => $uid, 'target_uid' => $essay['uid']])->find();
                    if ($res) {
                        $essay_list['is_fans'] = 1;
                    } else {
                        $essay_list['is_fans'] = 0;
                    }
                }
                return $essay_list;
            }
        }
    }

    public function searchEssay($keyword,$page = 1,$limit = 10)
    {
        return db('essay')
                ->field('eid,uid,content,img_url,create_time,like_count,comment_count')
                ->where('content','like','%'.$keyword.'%')
                ->where(['status'=>1])
                ->order(['create_time'=>'desc','is_recommend'=>'desc','order'=>'asc'])
                ->page($page)
                ->limit($limit)
                ->select();
    }

    public function getEssayReport($where)
    {
        return db('essay_reports')->where($where)->find();
    }

    public function addEssayReport($uid,$eid,$target_uid)
    {
        return db('essay_reports')->insert(['uid'=>$uid,'eid'=>$eid,'target_uid'=>$target_uid,'option'=>0,'create_time'=>date('Y-m-d H:i:s',time())]);
    }

    public function essayAllCount($where)
    {
        return db('essay')->where($where)->count();
    }


}